import chalk from 'chalk';
import fs from 'fs';
import path from 'path';
import download from 'download-git-repo';
import http from 'http';
import inquirer from 'inquirer';
import clui from 'clui';
const { Spinner } = clui;



const R = function (url) {
    return new Promise(function (resolve, reject) {
        try {
            http.get(url, function (data) {
                var str = "";
                data.on("data", function (chunk) {
                    str += chunk;//监听数据响应，拼接数据片段
                })
                data.on("end", function () {
                    resolve(str); //代码正常执行！
                })
            });
        } catch (error) {
            reject(error)
        }
    })
};


const changeVersion = async function () {

    var time = new Date().getTime();
    var _listStr = await R('http://192.168.3.106:88/BeCliConfig/project.json?t=' + time);
    var _listObj = JSON.parse(_listStr);
    var list = Object.keys(_listObj);

    const questions = [{
        type: "list",
        name: "formPath",
        message: "请选择需要创建的模板",
        choices: list,
        filter: function (val) {
            var src = _listObj[val];
            return src;
        }
    }];
    return inquirer.prompt(questions);
};

function delDir(path) {
    let files = [];
    if (fs.existsSync(path)) {
        files = fs.readdirSync(path);
        files.forEach((file, index) => {
            let curPath = path + "/" + file;
            if (fs.statSync(curPath).isDirectory()) {
                delDir(curPath); //递归删除文件夹
            } else {
                fs.unlinkSync(curPath); //删除文件
            }
        });
        fs.rmdirSync(path);
    }
}

const initProject = function () {
    const questions = [{
        type: "input",
        name: "folderName",
        message: "请输入项目名称",
    }];
    inquirer.prompt(questions).then(res => {
        var isExists = fs.existsSync(path.resolve(res.folderName));
        if (!isExists) {
            var toPath = path.resolve(res.folderName);

            changeVersion().then(res => {
                var countdown = new Spinner(chalk.blue('下载中...'), ['|', '/', '-', '\\', '-']);
                countdown.start();
                download('direct:' + res.formPath, toPath, { clone: true }, function (err) {
                    countdown.stop();
                    if (err) {
                        var scr = `
创建项目出错：1、请检查目录是否已经存在
              2、请检查gitlib是否已经登陆
              3、请检查网络连接状态是否正常`;
                        console.log(chalk.red(scr));
                    } else {
                        delDir(toPath + '/.git');
                        console.log(chalk.green(' ^_^ 下载成功'));
                    }
                })
            })
        } else {
            console.log(chalk.red('文件夹已存在'));
        }
    })
}

export default initProject